﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace GoPlay.Models
{
    public class EFRepository<T> : IRepository<T> where T : class, IEntity
    {
        private GoPlayDbContext _db = new GoPlayDbContext();


        public T GetByID(int id)
        {
            return _db.Set<T>().Where(x => x.Id == id).FirstOrDefault(); //Find(id);
        }

        public T GetByID(int id, string[] childCollectionNames)
        {
            T o = _db.Set<T>().Find(id);
            foreach (string s in childCollectionNames)
                _db.Entry(o).Collection(s).Load();
            return o;
        }

        public List<T> GetAllByUserId(int userId)
        {
            return _db.Set<T>().Where(x => x.UserId == userId).ToList();
        }

        public void Insert(T entity)
        {
            _db.Set<T>().Add(entity);
            _db.Entry<T>(entity).State = EntityState.Added;
        }

        public void SaveChanges()
        {
            _db.SaveChanges();
        }

        public void Delete(T entity)
        {
            _db.Set<T>().Attach(entity);
            _db.Entry<T>(entity).State = EntityState.Deleted;
        }

        public void Update(T entity)
        {
            _db.Set<T>().Attach(entity);
            _db.Entry<T>(entity).State = EntityState.Modified;
        }

    }
}